package com.book.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.book.model.Author;
import com.book.model.Readers;
import com.book.model.UserSent;
import com.book.result.Result;
import com.book.service.AuthorService;
import com.book.service.ReadersService;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@SpringBootTest
@RestController
@RequestMapping("register")
@Component
public class RegisterController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserSent userSent;

    @Autowired
    private AuthorService authorService;

    @Autowired
    private ReadersService readersService;

    @GetMapping("ReadersCode")
    public Result ReadersCode(String phone) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(userSent.getAccessKeyId())
                .accessKeySecret(userSent.getAccessKeySecret())
                .build());

        AsyncClient client = AsyncClient.builder()
                .region(userSent.getRegion())
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(userSent.getSetEndpointOverride())
                )
                .build();

        String code = RandomUtil.randomNumbers(6);
        redisTemplate.boundHashOps("ReadersCode").put(phone,code);
        redisTemplate.expire("ReadersCode",5000, TimeUnit.SECONDS);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",code);
        String s = JSONObject.toJSONString(jsonObject);

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(userSent.getSignName())
                .templateCode(userSent.getTemplateCode())
                .phoneNumbers(phone)
                .templateParam(s)
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(new Gson().toJson(resp));
        client.close();

        return Result.OK().setCode(code);
    }

    @GetMapping("AuthorCode")
    public Result AuthorCode(String phone) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(userSent.getAccessKeyId())
                .accessKeySecret(userSent.getAccessKeySecret())
                .build());

        AsyncClient client = AsyncClient.builder()
                .region(userSent.getRegion())
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(userSent.getSetEndpointOverride())
                )
                .build();

        String code = RandomUtil.randomNumbers(4);
        redisTemplate.boundHashOps("AuthorCode").put(phone,code);
        redisTemplate.expire("AuthorCode",5000, TimeUnit.SECONDS);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",code);
        String s = JSONObject.toJSONString(jsonObject);

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(userSent.getSignName())
                .templateCode(userSent.getTemplateCode())
                .phoneNumbers(phone)
                .templateParam(s)
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(new Gson().toJson(resp));
        client.close();

        return Result.OK().setCode(code);
    }

    @Test
    public void Test(){
        redisTemplate.boundZSetOps("TAG_NUM_COUNT_1").incrementScore("搞笑",1);
    }

    @PostMapping("ReadersRegister")
    public Result ReadersRegister(@RequestBody Readers readers,@RequestParam String phone,@RequestParam String code){
        Object dx = redisTemplate.boundHashOps("ReadersCode").get(phone);
        Result result = readersService.ReadersRegister(code, dx , readers);
        return result;
    }

    @PostMapping("AuthorRegister")
    public Result AuthorRegister(@RequestBody Author author, @RequestParam String phone, @RequestParam String code){
        Object dx = redisTemplate.boundHashOps("AuthorCode").get(phone);
        Result result = authorService.AuthorRegister(code, dx , author);
        return result;
    }
}
